/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lucky.blessing.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lucky.blessing.data.UserDataInfo;
import com.lucky.blessing.data.UserInfo;
import com.lucky.blessing.data.UserSumUrl;
import com.lucky.blessing.data.result.UserDataInfoResult;
import com.lucky.blessing.data.result.UserSumResult;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.lucky.blessing.DemoHelper;
import com.lucky.blessing.DemoModel;
import com.lucky.blessing.R;
import com.lucky.blessing.dialog.PayPassDialog;
import com.lucky.blessing.dialog.PayPassView;
import com.lucky.blessing.network.AppNetworkUtils;
import com.lucky.blessing.network.NetworkResultUtils;
import com.lucky.blessing.utils.PreferenceManager;
import com.lucky.blessing.utils.UserInfoUtils;
import com.hyphenate.easeui.model.EaseCompat;
import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.hyphenate.util.EMLog;
import com.mathum.baseapp.data.BaseData;
import com.mathum.baseapp.network.NetworkCallback;
import com.mathum.baseapp.network.NetworkUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * settings screen
 */
@SuppressWarnings({"FieldCanBeLocal"})
public class Settings2Fragment extends BaseActivity implements OnClickListener {

    /**
     * new message notification
     */
    private RelativeLayout rl_switch_notification;
    /**
     * sound
     */
    private RelativeLayout rl_switch_sound;
    /**
     * vibration
     */
    private RelativeLayout rl_switch_vibrate;
    /**
     * speaker
     */
    private RelativeLayout rl_switch_speaker;


    /**
     * line between sound and vibration
     */
    private TextView textview1, textview2;

    private LinearLayout blacklistContainer;

    private LinearLayout userProfileContainer;


    private LinearLayout userProfileContainer1;
    private LinearLayout userProfileContainer2;
    private LinearLayout userProfileContainer3;
    private LinearLayout userProfileContainer4;
    private LinearLayout userProfileContainer5;
    private LinearLayout userProfileContainer6;
    /**
     * logout
     */
    private Button logoutBtn;

    private RelativeLayout rl_switch_chatroom_leave;

    private RelativeLayout rl_switch_delete_msg_when_exit_group;
    private RelativeLayout rl_set_transfer_file_by_userself;
    private RelativeLayout rl_set_autodownload_thumbnail;
    private RelativeLayout rl_switch_auto_accept_group_invitation;
    private RelativeLayout rl_switch_adaptive_video_encode;
    private RelativeLayout rl_msg_roaming;
    private RelativeLayout rl_custom_appkey;
    private RelativeLayout rl_custom_server;
    RelativeLayout rl_push_settings;
    private LinearLayout ll_call_option;
    private LinearLayout ll_multi_device;
    private RelativeLayout rl_mail_log;
    // show "during typing" layout
    private RelativeLayout rl_msg_typing;

    /**
     * Diagnose
     */
    private LinearLayout llDiagnose;
    /**
     * display name for APNs
     */
    private LinearLayout pushNick;

    private EaseSwitchButton notifySwitch;
    private EaseSwitchButton soundSwitch;
    private EaseSwitchButton vibrateSwitch;
    private EaseSwitchButton speakerSwitch;
    private EaseSwitchButton ownerLeaveSwitch;
    private EaseSwitchButton switch_delete_msg_when_exit_group;
    private EaseSwitchButton set_transfer_file_by_userself;
    private EaseSwitchButton set_autodownload_thumbnail;
    private EaseSwitchButton switch_auto_accept_group_invitation;
    private EaseSwitchButton switch_adaptive_video_encode;
    private EaseSwitchButton customServerSwitch;
    private EaseSwitchButton customAppkeySwitch;
    private EaseSwitchButton switch_msg_Roaming;
    // show "during typing" switcher
    private EaseSwitchButton switch_msg_typing;
    private DemoModel settingsModel;
    private EMOptions chatOptions;
    private EditText edit_custom_appkey;
    private ImageView back;
    private TextView usernickText;
    private TextView usernickText1;
    private TextView usernickText2;
    private TextView usernickText3;
    private TextView usernickText4;
    private TextView usernickText5;
    private String userIDString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.em_fragment_conversation_settings2);
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        userIDString=UserInfoUtils.getAppUserId(Settings2Fragment.this);
        back = findViewById(R.id.back);
        rl_switch_notification = findViewById(R.id.rl_switch_notification);
        rl_switch_sound = findViewById(R.id.rl_switch_sound);
        rl_switch_vibrate = findViewById(R.id.rl_switch_vibrate);
        rl_switch_speaker = findViewById(R.id.rl_switch_speaker);
        rl_switch_chatroom_leave = findViewById(R.id.rl_switch_chatroom_owner_leave);
        rl_switch_delete_msg_when_exit_group = findViewById(R.id.rl_switch_delete_msg_when_exit_group);
        rl_set_transfer_file_by_userself = findViewById(R.id.rl_set_transfer_file_by_userself);
        rl_set_autodownload_thumbnail = findViewById(R.id.rl_set_autodownload_thumbnail);
        rl_switch_auto_accept_group_invitation = findViewById(R.id.rl_switch_auto_accept_group_invitation);
        rl_switch_adaptive_video_encode = findViewById(R.id.rl_switch_adaptive_video_encode);
        rl_custom_appkey = findViewById(R.id.rl_custom_appkey);
        rl_custom_server = findViewById(R.id.rl_custom_server);
//		rl_switch_offline_call_push =  (RelativeLayout) getView().findViewById(rl_switch_offline_call_push);
        rl_push_settings = findViewById(R.id.rl_push_settings);
        rl_msg_roaming = findViewById(R.id.rl_msg_roaming);

        ll_call_option = findViewById(R.id.ll_call_option);
        ll_multi_device = findViewById(R.id.ll_multi_device_management);

        rl_mail_log = findViewById(R.id.rl_mail_log);

        rl_msg_typing = findViewById(R.id.rl_msg_typing);

        notifySwitch = findViewById(R.id.switch_notification);
        soundSwitch = findViewById(R.id.switch_sound);
        vibrateSwitch = findViewById(R.id.switch_vibrate);
        speakerSwitch = findViewById(R.id.switch_speaker);
        ownerLeaveSwitch = findViewById(R.id.switch_owner_leave);
        switch_delete_msg_when_exit_group = findViewById(R.id.switch_delete_msg_when_exit_group);
        set_transfer_file_by_userself = findViewById(R.id.set_transfer_file_by_userself);
        set_autodownload_thumbnail = findViewById(R.id.set_autodownload_thumbnail);
        switch_auto_accept_group_invitation = findViewById(R.id.switch_auto_accept_group_invitation);
        switch_adaptive_video_encode = (EaseSwitchButton) findViewById(R.id.switch_adaptive_video_encode);
        switch_msg_Roaming = findViewById(R.id.switch_msg_roaming);
        switch_msg_typing = findViewById(R.id.switch_msg_typing);
        usernickText = findViewById(R.id.usernickText);
        usernickText1 = findViewById(R.id.usernickText1);
        usernickText2 = findViewById(R.id.usernickText2);
        usernickText3 = findViewById(R.id.usernickText3);
        usernickText4 = findViewById(R.id.usernickText4);
        usernickText5 = findViewById(R.id.usernickText5);

        logoutBtn = findViewById(R.id.btn_logout);
        if (!TextUtils.isEmpty(EMClient.getInstance().getCurrentUser())) {
            logoutBtn.setText(getString(R.string.button_logout) + "(" + EMClient.getInstance().getCurrentUser() + ")");
        }
        customServerSwitch = findViewById(R.id.switch_custom_server);
        customAppkeySwitch = findViewById(R.id.switch_custom_appkey);

        textview1 = findViewById(R.id.textview1);
        textview2 = findViewById(R.id.textview2);

        blacklistContainer = findViewById(R.id.ll_black_list);
        userProfileContainer = findViewById(R.id.ll_user_profile);

        userProfileContainer1 = findViewById(R.id.ll_user_profile1);
        userProfileContainer2 = findViewById(R.id.ll_user_profile2);
        userProfileContainer3 = findViewById(R.id.ll_user_profile3);
        userProfileContainer4 = findViewById(R.id.ll_user_profile4);
        userProfileContainer5 = findViewById(R.id.ll_user_profile5);
        userProfileContainer6 = findViewById(R.id.ll_user_profile6);

        llDiagnose = findViewById(R.id.ll_diagnose);
        pushNick = findViewById(R.id.ll_set_push_nick);
        edit_custom_appkey = findViewById(R.id.edit_custom_appkey);

        settingsModel = DemoHelper.getInstance().getModel();
        chatOptions = EMClient.getInstance().getOptions();

        back.setOnClickListener(this);
        blacklistContainer.setOnClickListener(this);
        userProfileContainer.setOnClickListener(this);

        userProfileContainer3.setOnClickListener(this);
        userProfileContainer4.setOnClickListener(this);
        userProfileContainer5.setOnClickListener(this);

        rl_switch_notification.setOnClickListener(this);
        rl_switch_sound.setOnClickListener(this);
        rl_switch_vibrate.setOnClickListener(this);
        rl_switch_speaker.setOnClickListener(this);
        customAppkeySwitch.setOnClickListener(this);
        customServerSwitch.setOnClickListener(this);
        rl_custom_server.setOnClickListener(this);
        logoutBtn.setOnClickListener(this);
        llDiagnose.setOnClickListener(this);
        pushNick.setOnClickListener(this);
        rl_switch_chatroom_leave.setOnClickListener(this);
        rl_switch_delete_msg_when_exit_group.setOnClickListener(this);
        rl_set_transfer_file_by_userself.setOnClickListener(this);
        rl_set_autodownload_thumbnail.setOnClickListener(this);
        rl_switch_auto_accept_group_invitation.setOnClickListener(this);
        rl_switch_adaptive_video_encode.setOnClickListener(this);
//		rl_switch_offline_call_push.setOnClickListener(this);
        rl_push_settings.setOnClickListener(this);
        ll_call_option.setOnClickListener(this);
        ll_multi_device.setOnClickListener(this);
        rl_mail_log.setOnClickListener(this);
        rl_msg_roaming.setOnClickListener(this);
        rl_msg_typing.setOnClickListener(this);

        // Add by zhangsong for service check.
        findViewById(R.id.ll_service_check).setOnClickListener(this);

        // the vibrate and sound notification are allowed or not?
        if (settingsModel.getSettingMsgNotification()) {
            notifySwitch.openSwitch();
        } else {
            notifySwitch.closeSwitch();
        }

        // sound notification is switched on or not?
        if (settingsModel.getSettingMsgSound()) {
            soundSwitch.openSwitch();
        } else {
            soundSwitch.closeSwitch();
        }

        // vibrate notification is switched on or not?
        if (settingsModel.getSettingMsgVibrate()) {
            vibrateSwitch.openSwitch();
        } else {
            vibrateSwitch.closeSwitch();
        }

        // the speaker is switched on or not?
        if (settingsModel.getSettingMsgSpeaker()) {
            speakerSwitch.openSwitch();
        } else {
            speakerSwitch.closeSwitch();
        }

        // if allow owner leave
        if (settingsModel.isChatroomOwnerLeaveAllowed()) {
            ownerLeaveSwitch.openSwitch();
        } else {
            ownerLeaveSwitch.closeSwitch();
        }

        // delete messages when exit group?
        if (settingsModel.isDeleteMessagesAsExitGroup()) {
            switch_delete_msg_when_exit_group.openSwitch();
        } else {
            switch_delete_msg_when_exit_group.closeSwitch();
        }

        if (settingsModel.isSetTransferFileByUser()) {
            set_transfer_file_by_userself.openSwitch();
        } else {
            set_transfer_file_by_userself.closeSwitch();
        }

        if (settingsModel.isSetAutodownloadThumbnail()) {
            set_autodownload_thumbnail.openSwitch();
        } else {
            set_autodownload_thumbnail.closeSwitch();
        }

        if (settingsModel.isAutoAcceptGroupInvitation()) {
            switch_auto_accept_group_invitation.openSwitch();
        } else {
            switch_auto_accept_group_invitation.closeSwitch();
        }

        if (settingsModel.isAdaptiveVideoEncode()) {
            switch_adaptive_video_encode.openSwitch();
            EMClient.getInstance().callManager().getCallOptions().enableFixedVideoResolution(false);
        } else {
            switch_adaptive_video_encode.closeSwitch();
            EMClient.getInstance().callManager().getCallOptions().enableFixedVideoResolution(true);
        }

        if (settingsModel.isCustomServerEnable()) {
            customServerSwitch.openSwitch();
        } else {
            customServerSwitch.closeSwitch();
        }

        if (settingsModel.isCustomAppkeyEnabled()) {
            customAppkeySwitch.openSwitch();
        } else {
            customAppkeySwitch.closeSwitch();
        }

        if (settingsModel.isMsgRoaming()) {
            switch_msg_Roaming.openSwitch();
        } else {
            switch_msg_Roaming.closeSwitch();
        }

        if (settingsModel.isShowMsgTyping()) {
            switch_msg_typing.openSwitch();
        } else {
            switch_msg_typing.closeSwitch();
        }

        edit_custom_appkey.setEnabled(settingsModel.isCustomAppkeyEnabled());

        edit_custom_appkey.setText(settingsModel.getCutomAppkey());
        edit_custom_appkey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                PreferenceManager.getInstance().setCustomAppkey(s.toString());
            }
        });

        usernickText.setText(UserInfoUtils.getNickName(this));
        NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().getUserDataInfo(userIDString),
                new NetworkCallback<UserDataInfoResult>() {
                    @Override
                    public void onSuccess(UserDataInfoResult userData) {
                        UserDataInfo dataInfo = userData.getUrl();
                        usernickText1.setText(dataInfo.getReal_name());
                        usernickText2.setText(dataInfo.getUser_idnumber());
                        usernickText3.setText(dataInfo.getUser_address());
                        usernickText4.setText(dataInfo.getUser_friend());
                        usernickText5.setText(dataInfo.getFriend_mobile());
                        if(dataInfo.getReal_name().trim().length()<2){
                            userProfileContainer1.setOnClickListener(Settings2Fragment.this);
                        }
                        if(dataInfo.getUser_idnumber().trim().length()<2){
                            userProfileContainer2.setOnClickListener(Settings2Fragment.this);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        final EditText et = new EditText(Settings2Fragment.this);
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rl_switch_notification:
                if (notifySwitch.isSwitchOpen()) {
                    notifySwitch.closeSwitch();
                    rl_switch_sound.setVisibility(View.GONE);
                    rl_switch_vibrate.setVisibility(View.GONE);
                    textview1.setVisibility(View.GONE);
                    textview2.setVisibility(View.GONE);
                    settingsModel.setSettingMsgNotification(false);
                } else {
                    notifySwitch.openSwitch();
                    rl_switch_sound.setVisibility(View.VISIBLE);
                    rl_switch_vibrate.setVisibility(View.VISIBLE);
                    textview1.setVisibility(View.VISIBLE);
                    textview2.setVisibility(View.VISIBLE);
                    settingsModel.setSettingMsgNotification(true);
                }
                break;
            case R.id.rl_switch_sound:
                if (soundSwitch.isSwitchOpen()) {
                    soundSwitch.closeSwitch();
                    settingsModel.setSettingMsgSound(false);
                } else {
                    soundSwitch.openSwitch();
                    settingsModel.setSettingMsgSound(true);
                }
                break;
            case R.id.rl_switch_vibrate:
                if (vibrateSwitch.isSwitchOpen()) {
                    vibrateSwitch.closeSwitch();
                    settingsModel.setSettingMsgVibrate(false);
                } else {
                    vibrateSwitch.openSwitch();
                    settingsModel.setSettingMsgVibrate(true);
                }
                break;
            case R.id.rl_switch_speaker:
                if (speakerSwitch.isSwitchOpen()) {
                    speakerSwitch.closeSwitch();
                    settingsModel.setSettingMsgSpeaker(false);
                } else {
                    speakerSwitch.openSwitch();
                    settingsModel.setSettingMsgVibrate(true);
                }
                break;
            case R.id.rl_switch_chatroom_owner_leave:
                if (ownerLeaveSwitch.isSwitchOpen()) {
                    ownerLeaveSwitch.closeSwitch();
                    settingsModel.allowChatroomOwnerLeave(false);
                    chatOptions.allowChatroomOwnerLeave(false);
                } else {
                    ownerLeaveSwitch.openSwitch();
                    settingsModel.allowChatroomOwnerLeave(true);
                    chatOptions.allowChatroomOwnerLeave(true);
                }
                break;
            case R.id.rl_switch_delete_msg_when_exit_group:
                if (switch_delete_msg_when_exit_group.isSwitchOpen()) {
                    switch_delete_msg_when_exit_group.closeSwitch();
                    settingsModel.setDeleteMessagesAsExitGroup(false);
                    chatOptions.setDeleteMessagesAsExitGroup(false);
                } else {
                    switch_delete_msg_when_exit_group.openSwitch();
                    settingsModel.setDeleteMessagesAsExitGroup(true);
                    chatOptions.setDeleteMessagesAsExitGroup(true);
                }
                break;
            case R.id.rl_set_transfer_file_by_userself:
                if (set_transfer_file_by_userself.isSwitchOpen()) {
                    set_transfer_file_by_userself.closeSwitch();
                    settingsModel.setTransfeFileByUser(false);
                    chatOptions.setAutoTransferMessageAttachments(false);
                } else {
                    set_transfer_file_by_userself.openSwitch();
                    settingsModel.setTransfeFileByUser(true);
                    chatOptions.setAutoTransferMessageAttachments(true);
                }
                break;
            case R.id.rl_set_autodownload_thumbnail:
                if (set_autodownload_thumbnail.isSwitchOpen()) {
                    set_autodownload_thumbnail.closeSwitch();
                    settingsModel.setAutodownloadThumbnail(false);
                    chatOptions.setAutoDownloadThumbnail(false);
                } else {
                    set_autodownload_thumbnail.openSwitch();
                    settingsModel.setAutodownloadThumbnail(true);
                    chatOptions.setAutoDownloadThumbnail(true);
                }
                break;
            case R.id.rl_switch_auto_accept_group_invitation:
                if (switch_auto_accept_group_invitation.isSwitchOpen()) {
                    switch_auto_accept_group_invitation.closeSwitch();
                    settingsModel.setAutoAcceptGroupInvitation(false);
                    chatOptions.setAutoAcceptGroupInvitation(false);
                } else {
                    switch_auto_accept_group_invitation.openSwitch();
                    settingsModel.setAutoAcceptGroupInvitation(true);
                    chatOptions.setAutoAcceptGroupInvitation(true);
                }
                break;
            case R.id.rl_switch_adaptive_video_encode:
                EMLog.d("switch", "" + !switch_adaptive_video_encode.isSwitchOpen());
                if (switch_adaptive_video_encode.isSwitchOpen()) {
                    switch_adaptive_video_encode.closeSwitch();
                    settingsModel.setAdaptiveVideoEncode(false);
                    EMClient.getInstance().callManager().getCallOptions().enableFixedVideoResolution(true);

                } else {
                    switch_adaptive_video_encode.openSwitch();
                    settingsModel.setAdaptiveVideoEncode(true);
                    EMClient.getInstance().callManager().getCallOptions().enableFixedVideoResolution(false);
                }
                break;
            case R.id.btn_logout:
                logout();
                break;
            case R.id.ll_black_list:
                startActivity(new Intent(this, BlacklistActivity.class));
                break;
            case R.id.ll_diagnose:
                startActivity(new Intent(this, DiagnoseActivity.class));
                break;
            case R.id.ll_set_push_nick:
                startActivity(new Intent(this, OfflinePushNickActivity.class));
                break;
            case R.id.ll_call_option:
                startActivity(new Intent(this, CallOptionActivity.class));
                break;
            case R.id.ll_multi_device_management:
                startActivity(new Intent(this, MultiDeviceActivity.class));
                break;
            case R.id.ll_user_profile:
                startActivity(new Intent(this, RegisterNicknameActivity.class).putExtra("userNickName", UserInfoUtils.getNickName(this)));
                break;

            case R.id.ll_user_profile1:
                Toast.makeText(getApplicationContext(), "真实姓名只能输入一次，请仔细很对", Toast.LENGTH_SHORT).show();
                et.setText(usernickText1.getText());
                new AlertDialog.Builder(Settings2Fragment.this).setTitle("真实姓名只能输入一次，请仔细很对")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String userEditString=et.getText().toString();
                                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().edituserinfo(userIDString,userEditString,"","","","",""),
                                        new NetworkCallback<BaseData>() {
                                            @Override
                                            public void onSuccess(BaseData baseData) {
                                                usernickText1.setText(userEditString);
                                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailure(Throwable t) {
                                                Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消",null).show();
                break;
            case R.id.ll_user_profile2:
                Toast.makeText(getApplicationContext(), "身份证号只能输入一次，请仔细很对", Toast.LENGTH_SHORT).show();
                et.setText(usernickText2.getText());
                new AlertDialog.Builder(Settings2Fragment.this).setTitle("身份证号只能输入一次，请仔细很对")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String userEditString=et.getText().toString();
                                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().edituserinfo(userIDString,"",userEditString,"","","",""),
                                        new NetworkCallback<BaseData>() {
                                            @Override
                                            public void onSuccess(BaseData baseData) {
                                                usernickText2.setText(userEditString);
                                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailure(Throwable t) {
                                                Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消",null).show();
                break;
            case R.id.ll_user_profile3:
                et.setText(usernickText3.getText());
                new AlertDialog.Builder(Settings2Fragment.this).setTitle("请输入您的地址")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String userEditString=et.getText().toString();
                                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().edituserinfo(userIDString,"","",userEditString,"","",""),
                                        new NetworkCallback<BaseData>() {
                                            @Override
                                            public void onSuccess(BaseData baseData) {
                                                usernickText3.setText(userEditString);
                                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailure(Throwable t) {
                                                Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消",null).show();
                break;
            case R.id.ll_user_profile4:
                et.setText(usernickText4.getText());
                new AlertDialog.Builder(Settings2Fragment.this).setTitle("请输入您好友的姓名")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String userEditString=et.getText().toString();
                                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().edituserinfo(userIDString,"","","",userEditString,"",""),
                                        new NetworkCallback<BaseData>() {
                                            @Override
                                            public void onSuccess(BaseData baseData) {
                                                usernickText4.setText(userEditString);
                                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailure(Throwable t) {
                                                Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消",null).show();
                break;
            case R.id.ll_user_profile5:
                et.setText(usernickText5.getText());
                new AlertDialog.Builder(Settings2Fragment.this).setTitle("请输入您好友的联系方式")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String userEditString=et.getText().toString();
                                NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().edituserinfo(userIDString,"","","","",userEditString,""),
                                        new NetworkCallback<BaseData>() {
                                            @Override
                                            public void onSuccess(BaseData baseData) {
                                                usernickText5.setText(userEditString);
                                                Toast.makeText(getApplicationContext(), "个人资料修改成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailure(Throwable t) {
                                                Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消",null).show();
                break;
            case R.id.ll_user_profile6:

                break;

            case R.id.switch_custom_server:
                if (customServerSwitch.isSwitchOpen()) {
                    customServerSwitch.closeSwitch();
                    settingsModel.enableCustomServer(false);
                } else {
                    customServerSwitch.openSwitch();
                    settingsModel.enableCustomServer(true);
                }
                break;
            case R.id.switch_custom_appkey:
                if (customAppkeySwitch.isSwitchOpen()) {
                    customAppkeySwitch.closeSwitch();
                    settingsModel.enableCustomAppkey(false);
                } else {
                    customAppkeySwitch.openSwitch();
                    settingsModel.enableCustomAppkey(true);
                }
                edit_custom_appkey.setEnabled(customAppkeySwitch.isSwitchOpen());
                break;
            case R.id.rl_msg_roaming:
                if (switch_msg_Roaming.isSwitchOpen()) {
                    switch_msg_Roaming.closeSwitch();
                    settingsModel.setMsgRoaming(false);
                } else {
                    switch_msg_Roaming.openSwitch();
                    settingsModel.setMsgRoaming(true);
                }
                break;
            case R.id.rl_custom_server:
                startActivity(new Intent(this, SetServersActivity.class));
                break;
            case R.id.rl_push_settings:

                startActivityForResult(new Intent(this, Register1Activity.class).putExtra("userPhone", UserInfoUtils.getPhone(this)),1);

//                startActivity(new Intent(this, OfflinePushSettingsActivity.class));
                break;
            case R.id.rl_mail_log:
                sendLogThroughMail();
                break;
            case R.id.ll_service_check:
                startActivity(new Intent(this, ServiceCheckActivity.class));
                break;
            case R.id.rl_msg_typing:
                if (switch_msg_typing.isSwitchOpen()) {
                    switch_msg_typing.closeSwitch();
                    settingsModel.showMsgTyping(false);
                } else {
                    switch_msg_typing.openSwitch();
                    settingsModel.showMsgTyping(true);
                }
                break;
            default:
                break;
        }
    }

    void logout() {
        final ProgressDialog pd = new ProgressDialog(this);
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        DemoHelper.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        // show login screen
                        getIntent().putExtra("action","logout");
                        setResult(Activity.RESULT_OK, getIntent());
                        finish();
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        pd.dismiss();
                        Toast.makeText(Settings2Fragment.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    void sendLogThroughMail() {
        String logPath = "";
        try {
            logPath = EMClient.getInstance().compressLogs();
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(Settings2Fragment.this, "compress logs failed", Toast.LENGTH_LONG).show();
                }
            });
            return;
        }
        File f = new File(logPath);
        File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (f.exists() && f.canRead()) {
            try {
                storage.mkdirs();
                File temp = File.createTempFile("hyphenate", ".log.gz", storage);
                if (!temp.canWrite()) {
                    return;
                }
                boolean result = f.renameTo(temp);
                if (result == false) {
                    return;
                }
                Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                intent.setData(Uri.parse("mailto:"));
                intent.putExtra(Intent.EXTRA_SUBJECT, "log");
                intent.putExtra(Intent.EXTRA_TEXT, "log in attachment: " + temp.getAbsolutePath());

                intent.setType("application/octet-stream");
                ArrayList<Uri> uris = new ArrayList<>();
                uris.add(EaseCompat.getUriForFile(this, temp));
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                startActivity(intent);
            } catch (final Exception e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Settings2Fragment.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            PayPassDialog payPassDialog=new PayPassDialog(Settings2Fragment.this);
            payPassDialog.getPayViewPass().setPayClickListener(new PayPassView.OnPayClickListener() {
                @Override
                public void onPassFinish(String passContent) {
                    final ProgressDialog pd = new ProgressDialog(Settings2Fragment.this);
                    pd.setMessage("正在处理，请稍后...");
                    pd.show();
                    NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().resetuserpaypass(userIDString,passContent),
                            new NetworkCallback<BaseData>() {
                                @Override
                                public void onSuccess(BaseData baseData) {
                                    if (!NetworkResultUtils.isSuccess(baseData)) {
                                        pd.dismiss();
                                        Toast.makeText(Settings2Fragment.this, baseData.getInfo(), Toast.LENGTH_LONG).show();
                                        return;
                                    }
                                    if (!Settings2Fragment.this.isFinishing()){
                                        pd.dismiss();
                                    }

                                    UserInfoUtils.setPayPassWord(passContent, Settings2Fragment.this);
                                    payPassDialog.dismiss();
                                    Toast.makeText(Settings2Fragment.this, "支付密码设置成功", Toast.LENGTH_LONG).show();
                                    finish();
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    pd.dismiss();
                                    Toast.makeText(Settings2Fragment.this, t.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            });

                }

                @Override
                public void onPayClose() {
                    payPassDialog.dismiss();
                }

                @Override
                public void onPayForget() {
                    payPassDialog.dismiss();
                }
            });
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        usernickText.setText(UserInfoUtils.getNickName(this));
    }

    @Override
    public void onResume() {
        super.onResume();
        //Toast.makeText(getActivity(), "提示：onResume", Toast.LENGTH_SHORT).show();
        usernickText.setText(UserInfoUtils.getNickName(this));
    }
}
